package com.atguigu.gulimall.finance.controller;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.finance.entity.TypeEntity;
import com.atguigu.gulimall.finance.entity.vo.TypeVo;
import com.atguigu.gulimall.finance.service.TypeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.Date;
import java.util.Map;


/**
 * 财务类型配置
 *
 * @author huguangwei
 * @email huguangwei@gmail.com
 * @date 2023-01-19 09:18:37
 */
@RestController
@RequestMapping("finance/type")
public class TypeController {
    @Autowired
    private TypeService typeService;

    /**
     * 列表
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = typeService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id) {
        TypeVo typeVo = typeService.getTypeById(id);

        return R.ok().put("type", typeVo);
    }

    /**
     * 保存
     */
    @PostMapping("/save")
    public R save(@RequestBody TypeEntity type) {
        type.setCreateTime(new Date());
        type.setUpdateTime(new Date());
        //查询类型名称是否存在
        TypeEntity typeEntity = typeService.getOne(new LambdaQueryWrapper<TypeEntity>().eq(TypeEntity::getTypeName, type.getTypeName()));
        if (typeEntity != null) {
            return R.error("类型已存在");
        } else {
            typeService.save(type);
        }

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    public R update(@RequestBody TypeEntity type) {
        type.setUpdateTime(new Date());
        //查询类型名称是否存在
        TypeEntity typeInfo = typeService.getById(type.getId());
        if (typeInfo != null) {
            if (!typeInfo.getTypeName().equals(type.getTypeName())) {
                TypeEntity typeEntity = typeService.getOne(new LambdaQueryWrapper<TypeEntity>().eq(TypeEntity::getTypeName, type.getTypeName()));
                if (typeEntity != null) {
                    return R.error("类型已存在");
                }
            }
            typeService.updateById(type);
            return R.ok();
        }
        return R.error("类型信息不存在");
    }

    /**
     * 删除
     */
    @RequestMapping("/delete")
    public R delete(@RequestBody Long[] ids) {
        typeService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
